<template>
  <div style="width: 100%; height: 100%" ref="chart" class="chart" />
</template>
<script>
import { debounce } from 'lodash';

export default {
  components: {},
  props: {
    option: Object,
    series: Array
  },
  name: 'BaseEchart',
  data () {
    return {
      chart: null,
      resizeObserver: undefined
    };
  },
  created () {
    this.debounceResize = debounce(this.resize, 500)
  },
  mounted () {
    window.addEventListener('resize', this.debounceResize);
    this.resizeObserver = new ResizeObserver(mutations => {
      this.debounceResize();
      this.resizeObserver.disconnect();
      this.resizeObserver = undefined;
    });
    this.resizeObserver.observe(this.$refs.chart);
    this.$nextTick(() => {
      this.init();
    })
  },
  methods: {
    // 双击事件
    dblNode () {
      this.chart?.off('dblclick'); // 关闭事件
      this.chart?.on('dblclick', (param) => {
        this.$emit('dblNode', param)
      });
    },
    init () {
      this.chart = this.$echarts.init(this.$refs.chart, {devicePixelRatio: 2});
      this.$emit('update:chart', this.chart)
      this.draw();
    },
    draw () {
      if (!this.chart) return;
      this.dblNode()
      this.$nextTick(() => {
        this.chart.setOption({
          ...this.option,
          series: [...this.series]
        }, true);
      });
    },
    resize () {
      this.$emit('resizeChange')
      this.chart.resize();
      this.draw();
    }
  },
  computed: {
    opt () {
      return {
        option: this.option,
        series: this.series
      }
    }
  },
  watch: {
    opt: {
      handler () {
        this.draw();
      },
      deep: true,
      immediate: true
    }
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.debounceResize)
    // this.resizeObserver.disconnect();
    // this.resizeObserver = undefined;
  }
};
</script>
<style lang="scss" scoped>

</style>
